package ar.com.cema.methodology.analyzer.ui.servlet.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import ar.com.cema.methodology.analyzer.exceptions.PersonInformationException;
import ar.com.cema.methodology.analyzer.exceptions.SurveyAlreadyAnsweredException;
import ar.com.cema.methodology.analyzer.model.Person;
import ar.com.cema.methodology.analyzer.model.Survey;
import ar.com.cema.methodology.analyzer.services.SurveyService;
import ar.com.cema.methodology.analyzer.ui.PageDirectory;
import ar.com.cema.methodology.analyzer.ui.ServiceLocator;

@WebServlet(name="StartQuestionnaireServlet", urlPatterns = { ServiceLocator.ACTION_START_QUESTIONNAIRE }) 
public class StartQuestionnaireServlet extends ActionServlet {
	private static final long serialVersionUID = 677666319152485634L;

	@Autowired
	private SurveyService surveyService;
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		String age = request.getParameter("age");
		String company = request.getParameter("company");
		String position = request.getParameter("position");
		String name = request.getParameter("name");

		Person person = new Person();
		person.setEmail(email);
		person.setAge(age);
		person.setCompany(company);
		person.setPosition(position);
		person.setName(name);
		
		List<String> errors = new ArrayList<String>();
		
		try {
			Survey survey = surveyService.createEmptySurveyFor(person);

			request.getSession().setAttribute("person", person);
			request.getSession().setAttribute("survey", survey);
			request.getServletContext().getRequestDispatcher(PageDirectory.SURVEY_QUESTIONNAIRE).forward(request, response);
			return;
		} catch (PersonInformationException e) {
			errors.add("Person information is incomplete!");
		} catch (SurveyAlreadyAnsweredException e) {
			errors.add("You have already complete the survey. Thanks a lot!");
		}

		request.setAttribute("errors", errors);
		request.getServletContext().getRequestDispatcher(PageDirectory.SURVEY_START).forward(request, response);
		return;
	}
	
	public void setSurveyService(SurveyService surveyService) {
		this.surveyService = surveyService;
	}
}